package br.com.persistencia;

import br.com.excecoes.DAOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;


/**
 *
 * @author Gernan
 */
public final class PersistenceUtil {

    private static String PERSISTENCE_NAME = "ControlePU";
    private static EntityManagerFactory factoryManager = null;
    private static EntityManager entityManager = null;

    private PersistenceUtil() {
    }

    private static EntityManagerFactory createEntityManagerFactory() throws DAOException {
        if (factoryManager == null || factoryManager.isOpen() == false) {
            try {
                factoryManager = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
            } catch (Exception e) {
                throw new DAOException("Problema ao tentar se conectar com o banco.\nVerifique o servidor.\nA aplicação será encerrada.");
            }
        }
        return factoryManager;
    }

    public static EntityManager getEntityManager() throws DAOException {
        if (entityManager == null || entityManager.isOpen() == false) {
            entityManager = createEntityManagerFactory().createEntityManager();
        }
        return entityManager;
    }

}
